package dao;

import domain.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.C3P0Utils;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by guo on 2017/10/31.
 */
public class DaoImpl implements Dao {
    @Override
    public List<Product> findAll() {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="select * from product";
        List list=null;
        try {
           list= (List) runner.query(sql,new BeanListHandler(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int delete(int pid) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="delete  from product where pid=?";
        int num=0;
        try {
           num = runner.update(sql, pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public List<Product> search(String pname) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="select * from product where pname like ?";
        String newsql="%"+pname+"%";
        List<Product> query=null;
        try {
             query =(List<Product>)runner.query(sql, new BeanListHandler(Product.class), newsql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public int add(Product product) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="insert into product(pname,market_price,pdesc) values(?,?,?)";
        int num=0;
        try {
        num = runner.update(sql, product.getPname(), product.getMarket_price(), product.getPdesc());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public Product findById(int pid) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="select * from product where pid=?";
        Product product=null;
        try {
            product= (Product) runner.query(sql,new BeanHandler(Product.class),pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return product;
    }

    @Override
    public int update(Product product) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDs());
        String sql="update product set pname=?,market_price=?,pdesc=? where pid=?";
        int num=0;
        try {
            num= runner.update(sql,product.getPname(),product.getMarket_price(),product.getPdesc(),product.getPid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }
}
